package com.hcloud.auth.api.token;

import com.hcloud.auth.api.user.MyUserDetail;
import com.hcloud.common.core.constants.AuthConstants;
import com.hcloud.system.core.bean.user.User;
import org.springframework.beans.BeanUtils;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.HashMap;
import java.util.Map;

/**
 * 自定义JwtAccessToken转换器
 * 用于扩展token，假如user信息
 */
public class MyJwtAccessTokenConverter extends JwtAccessTokenConverter {

    private DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();

    /**
     * 生成token
     * 在token中添加user的重要信息
     *https://blog.csdn.net/guduyishuai/article/details/80867400
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        MyUserDetail user = (MyUserDetail) authentication.getUserAuthentication().getPrincipal();

        final Map<String, Object> additionalInfo = new HashMap<>();
        User user1 = new User();
        BeanUtils.copyProperties(user.getBaseUser(),user1);
        user1.setPassword("");
        user1.setRole("");
        additionalInfo.put(AuthConstants.USER,user1);
        //user中已经包含权限信息，不再重复添加
//        additionalInfo.put(AuthConstants.AUTHORITY,user.getAuthorities());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return super.enhance(accessToken, authentication);
    }

    /**
     * 解析token
     *
     * @param value
     * @param map
     * @return
     */
    @Override
    public OAuth2AccessToken extractAccessToken(String value, Map<String, ?> map) {
        OAuth2AccessToken oauth2AccessToken = super.extractAccessToken(value, map);
        return oauth2AccessToken;
    }


    @Override
    public OAuth2Authentication extractAuthentication(Map<String, ?> map) {

        UserAuthenticationConverter userAuthenticationConverter =
                new AdditionalUserAuthenticationConverter();
        accessTokenConverter.setUserTokenConverter(userAuthenticationConverter);
        return accessTokenConverter.extractAuthentication(map);

    }

//    private BaseUser convertUserData(Object map) {
//        String json = JsonUtils.deserializer(map);
//        BaseUser user = JsonUtils.serializable(json, BaseUser.class);
//        return user;
//    }
}
